<template>
  <q-page class="wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image src="/svgs/titleIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'dataAnnotations' }">数据标注</el-breadcrumb-item>
        <el-breadcrumb-item><span style="color: #333;">标签管理</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="title">标签管理</div>
      <div class="contentBox">
        <el-row class="mb-4" style="margin-bottom: 15px">
          <div>
            <el-input v-model.trim="searchName" class="w-50 m-2" placeholder="搜索标签名称" :suffix-icon="Search"
                      spellcheck="false" />
          </div>
          <div class="rightBox">
            <el-button type="primary" size="small" @click="showCreateTag">添加标签</el-button>
          </div>
        </el-row>
        <el-table :data="filterTableData" stripe border style="width: 100%;font-size: 12px;"
                  :header-cell-style="{ background: '#eee', color: '#333333' }">
          <el-table-column align="center" prop="value" label="标签名称" />
          <el-table-column align="center" prop="version" label="标签颜色">
            <template #default="scope">
              <div class="colorSmallBox" :style="{ background: scope.row.background }"></div>
              <i style="font-style: initial;">{{ scope.row.background }}</i>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="description" label="备注" />
          <el-table-column align="center" prop="labels" label="操作" width="200">
            <template #default="{ row }">
              <el-button link type="primary" :disabled="row.count > 0" size="small" @click="setTagsData(row.value, row.description, row.background)">修改</el-button>
              <el-button link type="primary" size="small" @click="deleteTags(row.value)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog v-model="dialogNewVersion" title="新增标签" width="400" :show-close="false" :close-on-click-modal="false">
      <el-form ref="ruleFormRef" :model="addLabel" :rules="rules" label-position="right" label-width="100px"
        style="max-width: 500px" @submit.prevent>
        <el-form-item label="标签名称：" prop="value">
          <el-input v-model.trim="addLabel.value" input-style="width:180px" spellcheck="false" />
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model.trim="addLabel.description"
            input-style="width:200px"
            spellcheck="false"
            type="textarea"
            :rows="5" show-word-limit
            placeholder="请输入"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="标签颜色：">
          <el-color-picker v-model="addLabel.background" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">添加</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="setTags" title="修改标签" width="400" :show-close="false" :close-on-click-modal="false">
      <el-form ref="setRuleFormRef" :model="addLabel" :rules="setRules" label-position="right" label-width="100px"
        style="max-width: 500px" @submit.prevent>
        <el-form-item label="标签名称：" prop="value">
          <el-input v-model.trim="addLabel.value" input-style="width:180px" spellcheck="false" />
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model.trim="addLabel.description"
            input-style="width:200px"
            spellcheck="false"
            type="textarea"
            :rows="3" show-word-limit
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="标签颜色：">
          <el-color-picker v-model="addLabel.background" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setResetForm(setRuleFormRef)">取消</el-button>
          <el-button type="primary" @click="setSubmitForm(setRuleFormRef)">修改</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <q-dialog v-model="dialogDeleteData">
      <q-card style="width: 410px;padding: 0 20px">
        <q-card-section>
          <div class="text-h6" style="font-size: 17px;">
            <el-icon
              style="color: #FFA940;display: inline-block;vertical-align: middle;margin-top: -3px;font-size: 20px;">
              <WarningFilled />
            </el-icon>
            <span style="font-size: 16px;margin-left: 5px; color: #FFA940;">删除提醒</span>
          </div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          <div style="color: #666666e6;">确定删除以下1个标签吗？删除后不可恢复,请谨慎操作!</div>
        </q-card-section>
        <el-table
          :header-cell-style="{ background: '#eee', color: '#333333' }"
          :data="deleteDataList"
          style="width: 100%;">
          <el-table-column align="center" prop="value" label="标签名称" width="180" />
          <el-table-column align="center" prop="background" label="颜色" width="180" />
        </el-table>
        <q-card-actions align="right" class="text-primary" style="margin-right: 20px;margin-top: 10px">
          <el-button @click="deleteData">确认删除</el-button>
          <el-button type="primary" v-close-popup>放弃删除</el-button>
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>


<script setup lang="ts">
import { reactive, ref, shallowRef, computed } from "vue";
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import { dataSetStore } from 'src/stores/dataSet';
import {setLabelData, searchLabel, getDatasetDataList, deletedataLabel} from 'src/api/dataset'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const loading = ref(true)
const dialogNewVersion = ref(false)
const ruleFormRef = ref()
const setRuleFormRef = ref()
const setTags = ref(false)
const dialogDeleteData = ref(false);
const tagNameValue = ref('');
const addLabel = ref({
  value: '',
  description: '',
  background: '#629EFF'
});
import { Search } from '@element-plus/icons-vue'
let labelScene = ref('');//当前进入页面的标注场景
const setDataObj = ref({
  value: '',
  description: '',
  background: '#629EFF'
})
// 导入历史数据
const labelAssignData = ref([])
const rules = reactive<FormRules>({
  value: [
    { required: true, message: '标签名称不能为空', trigger: 'blur' }
  ]
})
const setRules = reactive<FormRules>({
  value: [
    { required: true, message: '标签名称不能为空', trigger: 'blur' }
  ]
});
const searchName = ref('')
const deleteDataList = ref([]);//删除展示的标签数据

getData()
function getData() {
  loading.value = false;
  let obj: obj = {
    label_task: dataSetStore().labelUseData.id
  }
  getDatasetDataList(projectId,dataSetStore().task_id,obj).then( (res:any) =>{
    labelScene.value = res.data.label_scene;
    if(
      res.data.label_scene === 'image_classification' ||
      // res.data.label_scene === 'outliers_and_anomaly_detection' ||
      // res.data.label_scene === 'signal_quality' ||
      // res.data.label_scene === 'time_series_forecasting' ||
      res.data.label_scene === 'taxonomy' ||
      res.data.label_scene === 'text_classification'
    ){
      labelAssignData.value = res.data.choices_statistic;
    } else {
      labelAssignData.value = res.data.label_statistic;
    }
  })
}
function showCreateTag() {
  dialogNewVersion.value = true
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogNewVersion.value = false
  setTags.value = false
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      setTagsApi(addLabel.value.value, 'add');
    } else {
      console.log('error submit!', fields)
    }
  })
}
const setResetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  setTags.value = false
}
const setSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      setTagsApi(setDataObj.value.value, 'set');
      formEl.clearValidate();
    } else {
      console.log('error submit!', fields)
    }
  })
};
let filterTableData = computed(() =>{
  return labelAssignData.value.filter((data: any) => data.value.toLowerCase().includes(searchName.value.toLowerCase()));
})


// 搜索标签
function searchTagList(){
  let params = {};
  if(searchName.value){
    params = { search_content: searchName.value };
  }
  searchLabel(projectId,dataSetStore().labelUseData.id,params).then( res => {
    labelAssignData.value = res.data;
  })
}
// 修改标签
function setTagsData(value: string, description: string , background: string) {
  setDataObj.value.value = value
  setDataObj.value.description = description
  setDataObj.value.background = background
  addLabel.value.value = value
  addLabel.value.description = description
  addLabel.value.background = background
  setTags.value = true
}
// 删除标签
function deleteTags(tagName: string) {
  dialogDeleteData.value = true;
  tagNameValue.value = tagName;
  deleteDataList.value = labelAssignData.value.filter((data: any) => {
    if( data.value === tagName ){
      return true
    }else {
      return false
    }
  });
}
function deleteData() {
  setTagsApi(tagNameValue.value, 'delete');
  dialogDeleteData.value = false;
}
// 数据操作
function setTagsApi(value: string, type: string) {
  let labelsArr = [...dataSetStore().labelsArr];
  let storeIndex = labelsArr.findIndex((item: any) => {
    return item.value == value
  })
  let tipsText = ''
  if (type == 'delete') {
    labelsArr.splice(storeIndex, 1)
    tipsText = '删除';
    labelsArr.forEach( items => {
      if(!items.description){
        delete items.description
      }
    });
  }
  if (type == 'set') {
    // if (storeIndex != -1 && labelsArr[storeIndex].value == addLabel.value.value) {
    //   ElMessage.error('输入标签名称与原标签名称一致，请重新输入')
    //   return
    // }
    labelsArr.splice(storeIndex, 1, addLabel.value);
    setTags.value = false
    tipsText = '修改';
    labelsArr.forEach( items => {
      if(!items.description){
        delete items.description
      }
    });
  }
  if (type == 'add') {
    labelsArr.push(addLabel.value)
    tipsText = '添加'
  }
  loading.value = true;
  // outliers_and_anomaly_detection
  // signal_quality
  let params:any = {};
  let arrayList:any = ['image_classification','time_series_forecasting','taxonomy','text_classification'];
  if( arrayList.includes(labelScene.value) ){
    params.choices = clean(labelsArr)
  }else{
    params.labels = clean(labelsArr)
  }
  setLabelData(projectId, dataSetStore().labelUseData.id, params).then((res: any) => {
    ElMessage.success(`${tipsText}成功`);
    // ElNotification({
    //   title: 'Success',
    //   message: `${tipsText}成功`,
    //   type: 'success',
    // });
    if(
      res.data.label_scene === 'image_classification' ||
      // res.data.label_scene === 'outliers_and_anomaly_detection' ||
      // res.data.label_scene === 'signal_quality' ||
      res.data.label_scene === 'time_series_forecasting' ||
      res.data.label_scene === 'taxonomy' ||
      res.data.label_scene === 'text_classification'
    ){
      labelAssignData.value = res.data.choices_statistic;
      dataSetStore().setLabelsArr(res.data.choices_statistic)
    } else {
      labelAssignData.value = res.data.label_statistic;
      dataSetStore().setLabelsArr(res.data.label_statistic)
    }
    dataSetStore().setUseData(res.data.id, res.data.annotation_config, res.data.data_type)
    dialogNewVersion.value = false
    // addLabel.value.description = '';
  }).catch(error => {
    labelsArr = [...dataSetStore().labelsArr]
  }).finally(() => {
    addLabel.value.value = ''
    loading.value = false
  })
}
function clean(ArrayList: { [x: string]: any; }) {
  ArrayList.forEach( (item:any) =>{
    for (let propName in item) {
      if (item[propName] === null || item[propName] === undefined || item[propName] === '') {
        delete item[propName];
      }
    }
    return item
  })
  return ArrayList
}
</script>

<style lang="scss" scoped>
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: #f6f8fa;
  height: 46px;
  ::v-deep .el-breadcrumb{
    display: flex;
    align-items: center;
  }
}
.wrapBox {
  padding: 0 !important;
  .datasetBox {
    margin: 0 20px;
    .title{
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}
//面包屑斜杆
::v-deep .el-breadcrumb__separator{
  font-size: 12px!important;
  color: #c9cdd4!important;
  margin-top: 2px!important;
}
//面包屑文字颜色
::v-deep .el-breadcrumb__inner{
  color: #666!important;
}
::v-deep .el-breadcrumb__inner.is-link, .el-breadcrumb__inner a{
  font-weight: normal!important;
}
.rightBox {
  position: absolute;
  right: 0;
}
::v-deep .el-message-box__message p{
  color: #ff5656!important;
}




.dataBox {
  .row {
    margin-bottom: 10px;

    i {
      font-style: initial;
      color: #333333;
    }
  }
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
  margin: 0 10px 0 -10px;
}

.successDot {
  background: #1FB62F;
}

.errorDot {
  background: #E6376E;
}

.colorSmallBox {
  display: inline-block;
  height: 10px;
  width: 10px;
  margin-right: 2px;
  border-radius: 2px;
}
</style>
